from fastapi import APIRouter, HTTPException, Depends, Query
from app.db.es_db import ElasticsearchClient
from typing import Dict, List, Any
from app.schemas.comment import CommentResponse

router = APIRouter()

@router.get("/", response_model=Dict[str, Any])
async def search_content(
    keyword: str,
    page: str = Query(default="1"),
    page_size: str = Query(default="10"),
    db: ElasticsearchClient = Depends(ElasticsearchClient)
):
    try:
        page_num = int(page)
        size = int(page_size)
        from_index = (page_num - 1) * size
        
        # 先获取总数
        count_query = {
            "query": {
                "match": {
                    "text": {
                        "query": keyword,
                        "fuzziness": "AUTO",
                        "operator": "or"
                    }
                }
            }
        }
        total_count = db.es.count(index="dian_li", body=count_query)
        print(total_count)
        # 构建分页搜索查询
        query = {
            "query": {
                "match": {
                    "text": {
                        "query": keyword,
                        "fuzziness": "AUTO",
                        "operator": "or"
                    }
                }
            },
            "sort": [{"_score": {"order": "desc"}}],
            "from": from_index,
            "size": size
        }
        
        # 执行搜索
        results = db.search("dian_li", query)
        # print(results)
        # hits = results.get("hits", {}).get("hits", [])
        
        items = [
            {
                "id": hit["_id"],
                "content": hit["_source"]["text"],
                "user": {
                    "name": "系统",
                    "avatar": "https://joeschmoe.io/api/v1/random"
                },
                "likes": 0,
                "replies": [],
                "createdAt": ""
            }
            for hit in results
        ]
        
        return {
            "items": items,
            "total": total_count["count"],  # 使用单独查询的总数
            "page": page_num,
            "page_size": size
        }
        
    except Exception as e:
        print(f"搜索失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))